int counter;
int i = 0;
int start = 0;
int fake_distance;

void setup() {

  counter = 0;
  Serial.begin(115200);

}

void loop() {
  
  if (start==1) {
    counter++;
    if (counter==361){
      counter=0;
      start=0;
    };

    Serial.print(char(0xA5)); // 1^ byte Header
    Serial.print(char(0x5A)); // 2^ byte Header
    
    Serial.print(char(0xFF)); // 1^ byte Quality
    
    if (counter > 255) {
      Serial.print(char(0x01)); // 1^ byte Angolo
      Serial.print(char(counter-255)); // 2^ byte Angolo  
    }
    else
    {
      Serial.print(char(0x00)); // 1^ byte Angolo
      Serial.print(char(counter)); // 2^ byte Angolo      
    }

    fake_distance = random(0,300);
    if (counter > 255) {
      Serial.print(char(0x01)); // 1^ byte Distanza
      Serial.print(char(fake_distance-255)); // 2^ byte Distanza  
    }
    else
    {
      Serial.print(char(0x00)); // 1^ byte Distanza
      Serial.print(char(fake_distance)); // 2^ byte Distanza      
    }
        
  }
  else {
    counter = 0;
  }
 
}

/*
  SerialEvent occurs whenever a new data comes in the
 hardware serial RX.  This routine is run between each
 time loop() runs, so using delay inside loop can delay
 response.  Multiple bytes of data may be available.
 */
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read(); 
    if (inChar == 'A') {
      start = 1;
      counter = 0;
    } 
    else if (inChar == 'B') {
      start = 0;
      counter = 0;
    } 
  }
}
